#!/usr/bin/env python3
"""
生成演示数据脚本
创建虚拟岗位信息和基于简历数据集的虚拟求职者
"""

import json
import pandas as pd
import random
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
import re

# 获取项目根目录
PROJECT_ROOT = Path(__file__).parent.parent
DATA_DIR = PROJECT_ROOT / "data"
RESUME_DATA_DIR = DATA_DIR / "resume_dataset"

class DemoDataGenerator:
    def __init__(self):
        self.companies = [
            "北京科技有限公司", "上海创新科技", "深圳智能科技", "杭州云计算公司", 
            "广州数据科技", "成都软件开发", "西安人工智能", "南京区块链科技",
            "武汉物联网公司", "天津金融科技", "重庆大数据", "苏州智慧科技",
            "青岛海洋科技", "大连软件园", "厦门移动互联", "长沙智能制造"
        ]
        
        self.skills_map = {
            "IT SOFTWARE": ["Python", "Java", "JavaScript", "React", "Vue.js", "Node.js", "MySQL", "MongoDB", "AWS", "Docker"],
            "ACCOUNTANT": ["财务分析", "税务处理", "成本控制", "预算管理", "审计", "Excel", "SAP", "会计准则"],
            "ADVOCATE": ["法律咨询", "合同审查", "诉讼代理", "法律研究", "风险评估", "法律文书"],
            "BANKING": ["风险管理", "信贷分析", "投资理财", "客户服务", "金融产品", "合规管理"],
            "AVIATION": ["飞行操作", "航空安全", "维护管理", "航线规划", "客户服务", "应急处理"],
            "AUTOMOBILE": ["汽车设计", "制造工艺", "质量控制", "供应链管理", "新能源技术"],
            "ARTS": ["创意设计", "视觉传达", "品牌策划", "用户体验", "多媒体制作"],
            "BPO": ["客户服务", "数据处理", "流程优化", "质量管理", "多语言能力"]
        }
        
        self.job_positions = {
            "IT SOFTWARE": [
                "高级Python开发工程师", "前端开发工程师", "全栈工程师", "数据科学家", 
                "算法工程师", "DevOps工程师", "产品经理", "技术总监"
            ],
            "ACCOUNTANT": [
                "财务经理", "会计主管", "成本会计", "税务专员", "审计经理", "财务分析师"
            ],
            "ADVOCATE": [
                "法务经理", "企业法律顾问", "合规专员", "知识产权专员", "法务助理"
            ],
            "BANKING": [
                "信贷经理", "风险控制专员", "理财经理", "客户关系经理", "合规经理"
            ],
            "AVIATION": [
                "飞行员", "航空维修工程师", "机务工程师", "航空安全员", "客舱经理"
            ],
            "AUTOMOBILE": [
                "汽车工程师", "质量工程师", "供应商管理", "产品经理", "研发工程师"
            ],
            "ARTS": [
                "UI/UX设计师", "平面设计师", "品牌经理", "创意总监", "视觉设计师"
            ],
            "BPO": [
                "客服专员", "数据分析师", "流程经理", "质量经理", "项目经理"
            ]
        }

    def load_resume_data(self):
        """加载简历数据"""
        try:
            resume_csv = RESUME_DATA_DIR / "Resume" / "Resume.csv"
            if resume_csv.exists():
                print(f"正在加载简历数据: {resume_csv}")
                df = pd.read_csv(resume_csv)
                print(f"成功加载 {len(df)} 条简历记录")
                return df
            else:
                print(f"简历数据文件不存在: {resume_csv}")
                return None
        except Exception as e:
            print(f"加载简历数据时出错: {e}")
            return None

    def extract_skills_from_resume(self, resume_text, category):
        """从简历文本中提取技能"""
        if not resume_text or pd.isna(resume_text):
            return self.skills_map.get(category, [])[:3]
        
        # 获取该类别的技能列表
        category_skills = self.skills_map.get(category, [])
        found_skills = []
        
        # 在简历文本中查找技能关键词
        resume_lower = resume_text.lower()
        for skill in category_skills:
            if skill.lower() in resume_lower:
                found_skills.append(skill)
        
        # 如果没找到足够技能，随机添加一些
        if len(found_skills) < 3:
            remaining_skills = [s for s in category_skills if s not in found_skills]
            additional_skills = random.sample(remaining_skills, min(3 - len(found_skills), len(remaining_skills)))
            found_skills.extend(additional_skills)
        
        return found_skills[:5]  # 最多返回5个技能

    def generate_virtual_jobs(self, num_jobs=50):
        """生成虚拟岗位信息"""
        jobs = []
        
        for i in range(num_jobs):
            # 随机选择行业类别
            category = random.choice(list(self.job_positions.keys()))
            position = random.choice(self.job_positions[category])
            company = random.choice(self.companies)
            
            # 生成薪资范围
            if "总监" in position or "经理" in position:
                salary_min = random.randint(15, 25) * 1000
                salary_max = salary_min + random.randint(8, 15) * 1000
            elif "专员" in position or "助理" in position:
                salary_min = random.randint(6, 12) * 1000
                salary_max = salary_min + random.randint(3, 8) * 1000
            else:
                salary_min = random.randint(10, 20) * 1000
                salary_max = salary_min + random.randint(5, 12) * 1000
            
            # 生成工作经验要求
            if "总监" in position:
                experience_min = random.randint(8, 12)
            elif "经理" in position:
                experience_min = random.randint(5, 8)
            elif "高级" in position:
                experience_min = random.randint(3, 6)
            else:
                experience_min = random.randint(1, 4)
            
            # 生成岗位描述
            skills = self.skills_map.get(category, [])[:5]
            description = f"""
岗位职责：
1. 负责{position}相关的日常工作
2. 参与项目规划和执行
3. 协助团队完成业务目标
4. 维护客户关系，提升服务质量

任职要求：
1. {experience_min}年以上相关工作经验
2. 具备{', '.join(skills[:3])}等技能
3. 良好的团队协作能力和沟通能力
4. 本科及以上学历优先

我们提供：
- 具有竞争力的薪资待遇
- 完善的培训体系
- 良好的职业发展空间
- 五险一金及其他福利
            """.strip()
            
            job = {
                "id": f"job_{i+1:03d}",
                "title": position,
                "company": company,
                "category": category,
                "location": random.choice(["北京", "上海", "深圳", "杭州", "广州", "成都"]),
                "salary_min": salary_min,
                "salary_max": salary_max,
                "experience_min": experience_min,
                "experience_max": experience_min + 3,
                "education": random.choice(["本科", "硕士", "专科"]),
                "employment_type": random.choice(["全职", "兼职", "实习"]),
                "required_skills": skills[:random.randint(3, 5)],
                "description": description,
                "benefits": ["五险一金", "带薪年假", "弹性工作", "技能培训", "年终奖金"],
                "posted_date": (datetime.now() - timedelta(days=random.randint(1, 30))).isoformat(),
                "deadline": (datetime.now() + timedelta(days=random.randint(15, 45))).isoformat(),
                "status": "active",
                "views": random.randint(50, 500),
                "applications": random.randint(5, 50)
            }
            jobs.append(job)
        
        return jobs

    def generate_virtual_candidates(self, resume_df, num_candidates=100):
        """基于简历数据生成虚拟求职者"""
        if resume_df is None or resume_df.empty:
            return []
        
        candidates = []
        
        # 随机选择简历记录
        selected_resumes = resume_df.sample(min(num_candidates, len(resume_df)))
        
        for idx, (_, row) in enumerate(selected_resumes.iterrows()):
            resume_text = row.get('Resume_str', '')
            category = row.get('Category', 'IT SOFTWARE')
            
            # 生成候选人基本信息
            first_names = ["张", "王", "李", "刘", "陈", "杨", "黄", "赵", "周", "吴"]
            second_names = ["伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军", "洋", "勇", "艳", "杰", "涛", "明", "超", "秀兰"]
            
            name = random.choice(first_names) + ''.join(random.choices(second_names, k=random.randint(1, 2)))
            
            # 生成邮箱
            email_domains = ["gmail.com", "163.com", "qq.com", "sina.com", "outlook.com"]
            email = f"{name.lower()}{random.randint(100, 999)}@{random.choice(email_domains)}"
            
            # 从简历中提取技能
            skills = self.extract_skills_from_resume(resume_text, category)
            
            # 生成工作经验
            experience_years = random.randint(1, 12)
            
            # 生成期望薪资
            if experience_years >= 8:
                expected_salary_min = random.randint(20, 35) * 1000
            elif experience_years >= 5:
                expected_salary_min = random.randint(15, 25) * 1000
            elif experience_years >= 3:
                expected_salary_min = random.randint(10, 18) * 1000
            else:
                expected_salary_min = random.randint(6, 12) * 1000
            
            expected_salary_max = expected_salary_min + random.randint(5, 10) * 1000
            
            # 生成个人简介
            position_preference = random.choice(self.job_positions.get(category, ["软件工程师"]))
            summary = f"""
{experience_years}年{category.lower()}行业经验，专注于{position_preference}相关工作。
具备{', '.join(skills[:3])}等核心技能，有丰富的项目开发和团队协作经验。
善于学习新技术，具有良好的问题解决能力和沟通协调能力。
希望在{category.lower()}领域继续发展，为团队和公司创造更大价值。
            """.strip()
            
            candidate = {
                "id": f"candidate_{idx+1:03d}",
                "name": name,
                "email": email,
                "phone": f"1{random.randint(3,8)}{random.randint(0,9):09d}",
                "age": random.randint(22, 45),
                "gender": random.choice(["男", "女"]),
                "location": random.choice(["北京", "上海", "深圳", "杭州", "广州", "成都", "西安", "南京"]),
                "education": random.choice(["本科", "硕士", "博士", "专科"]),
                "major": self.get_major_by_category(category),
                "experience_years": experience_years,
                "current_position": position_preference,
                "category": category,
                "skills": skills,
                "expected_salary_min": expected_salary_min,
                "expected_salary_max": expected_salary_max,
                "expected_location": random.choice(["北京", "上海", "深圳", "杭州"]),
                "employment_type": random.choice(["全职", "兼职"]),
                "summary": summary,
                "resume_text": resume_text[:1000] if resume_text else "",  # 截取前1000字符
                "availability": random.choice(["立即上岗", "1个月内", "2个月内", "3个月内"]),
                "created_date": (datetime.now() - timedelta(days=random.randint(1, 90))).isoformat(),
                "updated_date": (datetime.now() - timedelta(days=random.randint(1, 7))).isoformat(),
                "status": random.choice(["active", "passive", "not_available"]),
                "profile_views": random.randint(10, 200),
                "job_applications": random.randint(0, 15)
            }
            candidates.append(candidate)
        
        return candidates

    def get_major_by_category(self, category):
        """根据类别返回相关专业"""
        major_map = {
            "IT SOFTWARE": random.choice(["计算机科学与技术", "软件工程", "信息技术", "数据科学"]),
            "ACCOUNTANT": random.choice(["会计学", "财务管理", "审计学", "经济学"]),
            "ADVOCATE": random.choice(["法学", "知识产权法", "国际法", "商法"]),
            "BANKING": random.choice(["金融学", "经济学", "国际金融", "投资学"]),
            "AVIATION": random.choice(["航空航天工程", "飞行技术", "航空维修", "机械工程"]),
            "AUTOMOBILE": random.choice(["车辆工程", "机械工程", "汽车设计", "工业设计"]),
            "ARTS": random.choice(["视觉传达设计", "艺术设计", "数字媒体艺术", "广告学"]),
            "BPO": random.choice(["工商管理", "人力资源", "市场营销", "国际贸易"])
        }
        return major_map.get(category, "计算机科学与技术")

    def save_data(self, jobs, candidates):
        """保存生成的数据"""
        output_dir = DATA_DIR / "demo_data"
        output_dir.mkdir(exist_ok=True)
        
        # 保存岗位数据
        jobs_file = output_dir / "virtual_jobs.json"
        with open(jobs_file, 'w', encoding='utf-8') as f:
            json.dump(jobs, f, ensure_ascii=False, indent=2)
        print(f"已保存 {len(jobs)} 个虚拟岗位到: {jobs_file}")
        
        # 保存候选人数据
        candidates_file = output_dir / "virtual_candidates.json"
        with open(candidates_file, 'w', encoding='utf-8') as f:
            json.dump(candidates, f, ensure_ascii=False, indent=2)
        print(f"已保存 {len(candidates)} 个虚拟候选人到: {candidates_file}")
        
        # 生成统计报告
        self.generate_report(jobs, candidates, output_dir)

    def generate_report(self, jobs, candidates, output_dir):
        """生成数据统计报告"""
        report = {
            "generation_time": datetime.now().isoformat(),
            "total_jobs": len(jobs),
            "total_candidates": len(candidates),
            "job_categories": {},
            "candidate_categories": {},
            "salary_ranges": {},
            "experience_distribution": {}
        }
        
        # 统计岗位类别分布
        for job in jobs:
            category = job["category"]
            report["job_categories"][category] = report["job_categories"].get(category, 0) + 1
        
        # 统计候选人类别分布
        for candidate in candidates:
            category = candidate["category"]
            report["candidate_categories"][category] = report["candidate_categories"].get(category, 0) + 1
        
        # 统计薪资分布
        for job in jobs:
            salary_range = f"{job['salary_min']//1000}k-{job['salary_max']//1000}k"
            report["salary_ranges"][salary_range] = report["salary_ranges"].get(salary_range, 0) + 1
        
        # 统计经验分布
        for candidate in candidates:
            exp_range = f"{candidate['experience_years']//3*3}-{candidate['experience_years']//3*3+2}年"
            report["experience_distribution"][exp_range] = report["experience_distribution"].get(exp_range, 0) + 1
        
        # 保存报告
        report_file = output_dir / "generation_report.json"
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        print(f"已生成统计报告: {report_file}")

def main():
    print("🚀 开始生成演示数据...")
    
    generator = DemoDataGenerator()
    
    # 加载简历数据
    resume_df = generator.load_resume_data()
    
    # 生成虚拟岗位
    print("\n📋 生成虚拟岗位信息...")
    jobs = generator.generate_virtual_jobs(num_jobs=50)
    
    # 生成虚拟候选人
    print("\n👥 生成虚拟候选人...")
    candidates = generator.generate_virtual_candidates(resume_df, num_candidates=100)
    
    # 保存数据
    print("\n💾 保存生成的数据...")
    generator.save_data(jobs, candidates)
    
    print(f"\n✅ 演示数据生成完成！")
    print(f"   - 虚拟岗位: {len(jobs)} 个")
    print(f"   - 虚拟候选人: {len(candidates)} 个")
    print(f"   - 数据保存位置: {DATA_DIR / 'demo_data'}")

if __name__ == "__main__":
    main()